package cn.onlineclass.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@WebFilter(filterName = "role",value = "/*")
public class RoleFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("time init ");

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request =(HttpServletRequest)servletRequest;
        String path =request.getServletPath();
        //ip
        String ip = request.getRemoteAddr();
        if (ip.startsWith("192.168")){
            request.getRequestDispatcher("/login.jsp").forward(servletRequest,servletResponse);
            return;
        }

        System.out.println("进入了RoleFilter,当前正在验证:"+path);
        if (path.endsWith(".do")||path.endsWith("/login.jsp")||path.endsWith("/loginServlet")||path.endsWith(".css")||path.endsWith(".js")){
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }

        if (request.getSession().getAttribute("USER_LOGIN")==null){
            request.setAttribute("msg","你还没有登录");
            request.getRequestDispatcher("/login.jsp").forward(servletRequest,servletResponse);
            return;
        }
        filterChain.doFilter(servletRequest,servletResponse);
        System.out.println("离开了:RoleFilter");
    }

    @Override
    public void destroy() {
        System.out.println("time destroy ");
    }
}
